//
//  ActivityView.m
//  CheckIn
//
//  Created by bryan.ren on 27/01/2018.
//  Copyright © 2018 bryan. All rights reserved.
//

#import "ActivityView.h"
#import "WelcomePageData.h"
#import <AVKit/AVKit.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "CommonDefine.h"

static __strong UIWindow *activityWindow = nil;

@interface ActivityView () {
    NSArray *_activityArrays;
}

@property (nonatomic, strong) NSMutableArray<AVPlayerViewController *> *movieVcArray;
@property (nonatomic, strong) UIButton  *skipButton;

@end

@implementation ActivityView

+ (void)show
{
    WelcomePageData *pageData = [WelcomePageData new];
    pageData.welcomeImageReal = @"welcome_image.png";
    pageData.type = ActivityViewTypeImage;
    
    WelcomePageData *pageData1 = [WelcomePageData new];
    pageData1.welcomeImageReal = [[NSBundle mainBundle] pathForResource:@"qidong" ofType:@"mp4"];
    pageData1.type = ActivityViewTypeVideo;
    
    NSArray *validateArray = [NSArray arrayWithObjects:pageData1, pageData, nil];
    if(validateArray.count > 0)
    {
        [[UIApplication sharedApplication].keyWindow endEditing:YES];
        activityWindow = [[ActivityView alloc] initWithActivityArray:validateArray];
        [activityWindow setHidden:NO];
    }
}

- (instancetype)initWithActivityArray:(NSArray *)activityArray
{
    if (self = [super initWithFrame:[UIScreen mainScreen].bounds]) {
        _activityArrays = activityArray;
        self.windowLevel = UIWindowLevelAlert - 1;
        UIViewController *rootVC = [[UIViewController alloc] init];
        UIView *rootView = [[UIView alloc] initWithFrame:self.bounds];
        [rootVC setView:rootView];
        [self setRootViewController:rootVC];
        
        _scrollView = [self setScrollView];
        [_scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width * activityArray.count, _scrollView.frame.size.height)];
        [rootView addSubview:_scrollView];
        self.movieVcArray = [self movieVcs];
        [self activitySource];
        [rootView addSubview:[self pageControl]];
        [rootView addSubview:self.skipButton];
    }
    return self;
}

- (void)activitySource
{
    if (_activityArrays) {
        for (NSInteger i = 0; i < _activityArrays.count; i++)
        {
            WelcomePageData *pageData = _activityArrays[i];
            if (pageData.type == ActivityViewTypeImage) {
                UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(_scrollView.frame.size.width * i, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
                [imageView setClipsToBounds:YES];
                [imageView setContentMode:UIViewContentModeScaleAspectFill];
                [imageView setImage:[UIImage imageNamed:pageData.welcomeImageReal]];
                [_scrollView addSubview:imageView];
                
                AVPlayerViewController *movieVc = [[AVPlayerViewController alloc] init];
                movieVc.player = nil;
                [self.movieVcArray addObject:movieVc];
            }
            else if(pageData.type == ActivityViewTypeVideo) {
                NSURL *videoUrl = [NSURL fileURLWithPath:pageData.welcomeImageReal];
                if (videoUrl) {
                    AVPlayerViewController *movieVc = [[AVPlayerViewController alloc] init];
                    [self.movieVcArray addObject:movieVc];
                    [movieVc.view setFrame:CGRectMake(_scrollView.frame.size.width * i, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
                    movieVc.view.backgroundColor = [UIColor clearColor];
                    movieVc.showsPlaybackControls = NO;
                    AVAsset *asset = [AVAsset assetWithURL:videoUrl];
                    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
                    AVPlayer *player = [AVPlayer playerWithPlayerItem:item];
                    movieVc.player = player;
                    
                    for(UIView *aSubView in movieVc.view.subviews) {
                        aSubView.backgroundColor = [UIColor clearColor];
                    }
                    UIImage * image = [self loadFirstImage:videoUrl];
                    if (image) {
                        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
                        imageView.frame = CGRectMake(_scrollView.frame.size.width * i, 0, _scrollView.frame.size.width, _scrollView.frame.size.height);
                        imageView.contentMode = UIViewContentModeScaleAspectFill;
                        [_scrollView addSubview:imageView];
                    }
                    [_scrollView addSubview:movieVc.view];
                    if (_activityArrays.count == 1 || (_activityArrays.count > 1 && i == 0)) {
                        [movieVc.player play];
                    }
                }
            }
        }
    }
}

//获取视频的第一帧图片
- (UIImage*) loadFirstImage : (NSURL *) vidURL {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:vidURL options:nil];
    float fps = [[[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] nominalFrameRate];
    AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset]; // Create object of Video.
    
    NSError *err = NULL;
    
    CMTime time = CMTimeMake(1, fps); // Select time of 1/60ths of a second.
    
    CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err]; // Get Image on that time frame.
    
    NSLog(@"err==%@, imageRef==%@", err, imgRef); // if something is not as expected then u can log error.
    
    return [[UIImage alloc] initWithCGImage:imgRef]; // Convert Image from CGImage to UIImage so you can display it easily in a image view.
}

- (void)skipButtonAction
{
    [self removeMovieVcs];
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 0.f;
    } completion:^(BOOL finished) {
        [self setHidden:YES];
        activityWindow = nil;
    }];
}

- (void) removeMovieVcs {
    for (NSInteger i=0; i<self.movieVcArray.count; ++i) {
        AVPlayerViewController *movieVc = [self.movieVcArray objectAtIndex:i];
        if (movieVc && movieVc.player) {
            [movieVc.player pause];
            [movieVc.view removeFromSuperview];
        }
    }
    [self.movieVcArray removeAllObjects];
}

#pragma mark - scrollview delegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x / scrollView.frame.size.width;
//    if (index == _activityArrays.count - 1) {
//        [self.skipButton setHidden:NO];
//    }
//    else {
//        [self.skipButton setHidden:YES];
//    }
    _pageControl.currentPage = index;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat index = scrollView.contentOffset.x / scrollView.frame.size.width;
    [self.skipButton setAlpha:index];
}

- (UIScrollView *)setScrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        [_scrollView setPagingEnabled:YES];
        [_scrollView setDelegate:self];
        [_scrollView setShowsHorizontalScrollIndicator:NO];
        [_scrollView setBounces:NO];
    }
    return _scrollView;
}

- (NSMutableArray<AVPlayerViewController *> *)movieVcs
{
    if (self.movieVcArray == nil) {
        self.movieVcArray = [NSMutableArray<AVPlayerViewController *> array];
    }
    else {
        [self.movieVcArray removeAllObjects];
    }
    return self.movieVcArray;
}

- (UIButton *)skipButton
{
    if (!_skipButton) {
        _skipButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_skipButton setFrame:CGRectMake(60, scr_height - 160, scr_width - 120, 60)];
        [_skipButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_skipButton setTitle:@"开始工作" forState:UIControlStateNormal];
        [_skipButton addTarget:self action:@selector(skipButtonAction) forControlEvents:UIControlEventTouchUpInside];
        [_skipButton setAlpha:0];
    }
    return _skipButton;
}

- (UIPageControl *)pageControl
{
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, scr_height - 40, scr_width, 40)];
        [_pageControl setUserInteractionEnabled:NO];
        [_pageControl setHidesForSinglePage:YES];
        [_pageControl setNumberOfPages:_activityArrays.count];
    }
    return _pageControl;
}

@end
